<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <!-- 提示区域 -->
            <el-alert title="添加商品信息" type="info" center show-icon :closable="false">
            </el-alert>
            <!-- 步骤条 -->
            <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <!-- tabs标签页 -->
            <el-form :model="AddForm" :rules="AddFormRules" ref="AddFormRef" label-width="100px" label-position="top">
                <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeTabLeave"
                    @tab-click="tabClicked">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="AddForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="AddForm.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="AddForm.goods_weight" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="AddForm.goods_number" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader expand-trigger="hover" :options="CateList" v-model="AddForm.goods_cat"
                                :props="CateProps" @change="handleChange">
                            </el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <!-- 渲染表单item项 -->
                        <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
                            <!-- 复选框组 -->
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox border :label="item1" v-for="(item1,index) in item.attr_vals" :key="index">
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <!-- 上传图片 -->
                        <el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove"
                            list-type="picture" :headers="headerObj" :on-success="handleSuccess">
                            <!-- headers设置请求头-->
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <!-- 富文本编辑器组件 -->
                        <quill-editor v-model="AddForm.goods_introduce"></quill-editor>
                        <!-- 添加商品按钮 -->
                        <el-button type="primary" style="margin:15px 0;" @click="add">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
        <!-- 图片预览dialog -->
        <el-dialog title="提示" :visible.sync="previewVisibile" width="50%">
            <img :src="previewPath" alt="" class="previewImg">
        </el-dialog>
    </div>
</template>

<script>
    import _ from 'lodash'
    export default {
        data() {
            return {
                activeIndex: '0',
                AddForm: {
                    goods_name: '', //商品名称
                    goods_price: 1, //商品价格
                    goods_weight: 1,  //商品种类
                    goods_number: 1, //商品数量
                    goods_cat: [], //商品所属的分类数组
                    pics: [

                    ], //图片数组
                    goods_introduce: '', //富文本编辑器商品详情描述
                    attrs: [], //添加商品功能提交的参数
                }, //添加表单数据对象
                CateList: [], //商品分类列表
                CateProps: {
                    label: 'cat_name',
                    value: 'cat_id',
                    children: 'children'
                },
                manyTableData: [], //动态many列表数据
                onlyTableData: [], //静态only列表数据
                AddFormRules: {
                    goods_name: [
                        { required: true, message: '请输入商品名称', trigger: 'blur' }
                    ],
                    goods_price: [
                        { required: true, message: '请输入商品价格', trigger: 'blur' }
                    ],
                    goods_weight: [
                        { required: true, message: '请输入商品重量', trigger: 'blur' }
                    ],
                    goods_number: [
                        { required: true, message: '请输入商品数量', trigger: 'blur' }
                    ],
                    goods_cat: [
                        { required: true, message: '请输入商品分类', trigger: 'blur' }
                    ]
                }, //验证规则
                uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload', //上传图片的URL地址
                headerObj: {
                    Authorization: window.sessionStorage.getItem('token')
                },//图片上传headers请求头
                previewPath: '', //预览图片的图片url
                previewVisibile: false,
            }
        },
        created() {
            this.getCateList();
        },
        methods: {
            // 获取级联样式表所有商品分类数据
            async getCateList() {
                const { data: res } = await this.$http.get('categories');
                if (res.meta.status == 200) {
                    this.CateList = res.data;
                    this.$message.success('获取商品数据成功');
                } else {
                    this.$message.error('获取商品失败');
                }
            },
            // 级联选择器change事件
            handleChange() {
                if (this.AddForm.goods_cat.length !== 3) {
                    this.AddForm.goods_cat = []
                    this.$message.error('选择分类必须是三级分类');
                }
            },
            // 阻止Tabs标签页切换
            beforeTabLeave(ActiveName, oldActiveName) {
                if (oldActiveName == '0' && this.AddForm.goods_cat.length != 3) {
                    this.$message.error('请选择商品分类');
                    return false;
                } else {
                    return true;
                }
            },
            // Tabs标签切换事件
            async tabClicked() {
                //判断点击的是那个标签页
                if (this.activeIndex == '1') {
                    const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
                        params: { sel: 'many' }
                    });
                    if (res.meta.status == 200) {
                        console.log(res.data);
                        res.data.forEach(item => {
                            if (item.attr_vals.length == 0) {
                                item.attr_vals = [];
                            } else {
                                item.attr_vals = item.attr_vals.split(',');
                            }
                        })
                        this.manyTableData = res.data;
                        this.$message.success('获取动态参数列表成功!');
                    } else {
                        this.$message.error('获取动态参数列表失败!');
                    }
                } else if (this.activeIndex == '2') {
                    const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
                        params: { sel: 'only' }
                    });
                    if (res.meta.status == 200) {
                        console.log(res.data);
                        this.onlyTableData = res.data;
                    } else {
                        this.$message.error('获取静态属性失败');
                    }
                }
            },
            // 处理图片预览效果
            handlePreview(file) {
                this.previewPath = file.response.data.url
                this.previewVisibile = true;
            },
            // 删除图片信息
            handleRemove(file) {
                //需要删除文件的临时路径
                const filePath = file.response.data.tmp_path;
                //查询addform数组里pics里的每一项如果找到判断条件的哪一项就不再查找
                const i = this.AddForm.pics.findIndex(item => {
                    if (item.pic == filePath) {
                        this.AddForm.pics.splice(i, 1);
                        console.log(this.AddForm)
                    }
                })
            },
            // 监听上传图片成功
            handleSuccess(response) {
                const picInfo = {
                    pic: response.data.tmp_path
                }
                this.AddForm.pics.push(picInfo)
                console.log(this.AddForm)
            },
            //
            add() {
                this.$refs.AddFormRef.validate(async valid => {
                    if (!valid) {
                        this.$message.error('请填写必要表单项');
                    } else {
                        // lodash cloneDeep(obj)                     
                        // const form = _.cloneDeep(this.AddForm)
                        // form.goods_cat = form.goods_cat.join(',')
                        this.AddForm.goods_cat = this.AddForm.goods_cat.join(",");
                        this.manyTableData.forEach(item => {
                            const newInfo = {
                                attr_id: item.attr_id,
                                attr_value: item.attr_vals.join(' ')
                            }
                            this.AddForm.attrs.push(newInfo);
                        })
                        this.onlyTableData.forEach(item => {
                            const newInfo = {
                                attr_id: item.attr_id,
                                attr_value: item.attr_vals
                            }
                            this.AddForm.attrs.push(newInfo);
                        })
                        // form.attrs = this.AddForm.attrs                      
                        console.log(this.AddForm)
                        //发起请求,商品名称必须是唯一的
                        const { data: res } = await this.$http.post('goods', this.AddForm);
                        if (res.meta.status == 201) {
                            this.$router.push('/goods')
                            this.$message.success('添加商品成功');
                        } else {
                            this.$message.error('添加商品失败');
                        }
                    }
                })
            }
        },
        computed: {
            cateId() {
                if (this.AddForm.goods_cat.length == 3) {
                    return this.AddForm.goods_cat[2];
                } else {
                    return null;
                }
            }
        },
    }

</script>

<style lang="scss" scoped>
    .el-checkbox {
        margin: 0 5px 0 0 !important;
    }

    .previewImg {
        width: 100%;
    }
</style>